<?php
namespace app\web\controller;
use app\web\model\LineShiftModel;
use app\common\controller\StoreBaseController;
use think\Db;
/**
 * 商户后台首页
 * @author Kaisa
 * @version 2017-02-09 17:00:00
 */
class IndexController extends StoreBaseController {
 	protected $model;
	
    protected function _initialize() {
        parent::_initialize();
        $this->model = new LineShiftModel();
    }	
	
	/**
	 * 首页
	 */	
	public function index(){
		$store_id = session('storeInfo')['id'];
		//线上订单
        $where_order['agent_id']=$store_id;
		$field=("id,order_state,total_price,pay_time");
		$to_fahuo=0;//待发货
		$to_pay=0;//待付款
		$to_wancheng=0;//已完成
		$ordersum=0;//订单总数
		$moneysum=0;//线上累计销售
		$todaymoneysum=0;//今天销售
		$weekmoneysum=0;//本周销售
		$orders=Db::name("mall_order")->where($where_order)->field($field)->cache(120)->select();
		foreach($orders as $o){
		    	$ordersum++;
		    	$o_status=$o['order_state'];
		        if($o_status==5){
		        	$to_wancheng++;
					$moneysum=$moneysum+floatval($o['total_price']);
		        }else if($o_status==3){
		        	$to_fahuo++;
		        }else if($o_status==2){
		        	$to_pay++;
		        }
				if(isToday($o['pay_time'])){
					$todaymoneysum=$todaymoneysum+floatval($o['total_price']);
					$weekmoneysum=$weekmoneysum+floatval($o['total_price']);
				}else{
					if(isToday($o['pay_time'])){
						$weekmoneysum=$weekmoneysum+floatval($o['total_price']);
					}
				}
		    }
		$this->assign("ordersum",$ordersum);
		$this->assign("to_pay",$to_pay);
		$this->assign("to_fahuo",$to_fahuo);
		$this->assign("to_wancheng",$to_wancheng);
		$this->assign('moneysum',$moneysum);
		$this->assign('todaymoneysum',$todaymoneysum);	
		$this->assign('weekmoneysum',$weekmoneysum);
		
		$totalsum=Db::name("member")->cache(60)->count('id');
		$totalsum=$totalsum?$totalsum:0;  //线上会员总数
        $this->assign('totalsum',$totalsum);
        
		$todaysum = Db::name("member")->whereTime('add_time','today')->cache(60)->count('id');
		$todaysum=$todaysum?$todaysum:0;
		$this->assign('todaysum',$todaysum);
		
        $weeksum = Db::name("member")->whereTime('add_time','week')->cache(60)->count('id');
        $weeksum=$weeksum?$weeksum:0;
        $this->assign('weeksum',$weeksum);
		
        //线上商品（已售0）
        $agent_id = session('storeInfo')['id'];
        //总数       
        $ysums = Db::name("line_goods")->field('id')->where('store_id',$agent_id)-> cache(60)->count('id');
		$sales = Db::name("line_goods")->field('id')->where('store_id',$agent_id)-> cache(60)->sum('sales');
		$this->assign('ysums',$ysums);
		$this->assign('sales',$sales);

		$totalcoms=db("mall_comment")->where("agent_id",$store_id)->count('id');
		$this->assign('totalcoms',$totalcoms?$totalcoms:0);
		//收入
		
        
		//显示最新注册的10位会员
		//$store_id = session('storeInfo')['u_id'];
		$field = 'id,uid,member_no,member_gradeid,membername,store_id,store_name,reg_date';		
		$where['store_id']=$store_id;
		$line_member=db("line_member")->field($field)->where($where)->order("reg_date desc")->paginate(10);
		//最新的10笔订单
		$order_field = 'a.id,a.sn,a.price,a.status,a.agent_id,a.line_member_id,a.pay_time,m.id,m.membername';		
		$order_where['a.agent_id']=$store_id;
		$order_where['a.status']=2;
		$order_new=db("line_order")->alias('a')->join('line_member m','a.line_member_id=m.id')->field($order_field)->where($order_where)->order("pay_time desc")->paginate(10);
		//echo db('line_order')->getlastsql();die;

		return $this -> fetch('index',['line_member'=>$line_member,'order_new'=>$order_new]);
	}

	
	
	/**
     * 更新
     */
    public function update() {
        if (request()->isPost()) {
        	
        }else{
        	$agent = db('mall_agent')->find(session('storeInfo')['id']);
        	return $this->fetch('update', ['agent' => $agent]);
        }
    }
	
	/**
     * 更新密码
     */
    public function password() {
        if (request()->isPost()) {
	      /*	$data = request()->post();
			if(empty($data['old_pwd'])){
				$this->error('请输入旧密码');
			}
			if(empty($data['login_pwd']) || empty($data['login_pwd2'])){
				$this->error('请输入新密码');
			}
			if($data['login_pwd'] != $data['login_pwd2']){
				$this->error('二次密码输入不一致');
			}
            $agent = db('mall_agent')->find(session('storeInfo')['id']);
			if(md5_salt($data['old_pwd'])!=$user['login_pwd']){
				$this->error('旧密码错误');
			}
            $update_data['login_pwd'] = md5_salt($data['login_pwd']);
            if (db('user')->where('id',session('admin_id'))->update($update_data) !== false) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }*/
			$this->error('更新失败');
        }else{
        	$user = db('user')->find(session('admin_id'));
        	return $this->fetch('password', ['user' => $user]);
        }
    }
	
	/**
     * 清除缓存
     */
    public function clear() {
        if (delete_dir_file(CACHE_PATH) || delete_dir_file(TEMP_PATH)) {
            $this->success('清除缓存成功');
        } else {
            $this->error('清除缓存失败');
        }
    }
	
	 /**
     * 交班记录
     * @author [lx] 
     */
    public function jiaoban_list(){
    	$agent_id = session('storeInfo')['id'];

		$where['store_id'] = $agent_id;
		$where['add_time'] = ['>=',date('Y-m-d 00:00:00',time())];
		//交班记录表今天是否存在记录，存在获取最新的
		$shift = Db::name("line_shift")->where($where)->limit(1)->order('add_time desc')->find();
		
		$map['agent_id'] = $agent_id;
		$map['money_type'] = 1;
		$map['status'] = 2;
		
		if($shift){
			$startime = $shift['add_time'];
			$map['add_time'] = ['between',[$shift['add_time'],now_time()]];
		}else{
			//记录表没有记录
			$startime = date('Y-m-d 00:00:00',time());
			$map['add_time'] = ['between',[date('Y-m-d 00:00:00',time()),now_time()]];
		}
		
		//获取充值收入
		$xianjin = $this->getxf('1',$map);
		$yinhangka = $this->getxf(5,$map);
		$weixin = $this->getxf(3,$map);
		$zhifubao = $this->getxf(4,$map);
		$zidingyi = $this->getxf(6,$map);
		
		
		//今日现金充值收入
    	$map1['store_id'] = $agent_id;
		$map1['status'] = 2;
		if($shift){
			$map1['add_time'] = ['between',[$shift['add_time'],now_time()]];
		}else{
			//记录表没有记录
			$map1['add_time'] = ['between',[date('Y-m-d 00:00:00',time()),now_time()]];
		}
		
		//获取充值收入
		$xianjincz = $this->getcz(1,$map1);
		$yinhangkacz = $this->getcz(2,$map1);
		$weixincz = $this->getcz(3,$map1);
		$zhifubaocz = $this->getcz(4,$map1);
		$zidingyicz = $this->getcz(5,$map1);	
	
		//获取充次收入
		$xianjincc = $this->getcc(1,$map1);
		$yinhangkacc = $this->getcc(5,$map1);
		$weixincc = $this->getcc(3,$map1);
		$zhifubaocc = $this->getcc(4,$map1);
		$zidingyicc = $this->getcc(6,$map1);			
		
		//今日现金收入
		$xj = $xianjin+$xianjincc+$xianjincz;
		//今日银行卡收入
		$yhk = $yinhangka+$yinhangkacc+$yinhangkacz;
		//今日微信收入
		$wx = $weixin+$weixincc+$weixincz;
		//今日支付宝收入
		$zfb = $zhifubao+$zhifubaocc+$zhifubaocz;
		//今日自定义收入
		$zdy = $zidingyi+$zidingyicc+$zidingyicz;
		
		//今日总收入
		$zsr = $xj+$yhk+$wx+$zfb+$zdy;
		
		$data['xianjin'] = $xj;
		$data['yinhangka'] = $yhk;
		$data['weixin'] = $wx;
		$data['zhifubao'] = $zfb;
		$data['zidingyi'] = $zdy;
		$data['zsr'] = $zsr;
		$data['startime'] = $startime;
		$data['endtime'] = now_time();
        return json(['code'=>200,'data'=>$data]);
    }

	//获取今日消费收入
	public function getxf($id,$map){
		$xiaofei = Db::name("line_order")->where($map)->where('pay_method',$id)->sum('price');
        if($xiaofei){
			$xiaofei=$xiaofei;				
		}else{
			$xiaofei=0;
		}		
		return $xiaofei;
	}

	//获取今日充值
	public function getcz($id,$map){
        $chongzhi = Db::name("line_rechlog")->where($map)->where('pay_method',$id)->sum('price');
        if($chongzhi){
			$chongzhi=$chongzhi;				
		}else{
			$chongzhi=0;
		}	
		
		return $chongzhi;
	}

	//获取今日充次
	public function getcc($id,$map){
		$chongci = Db::name("line_memchargelog")->where($map)->where('pay_method',$id)->sum('price');
        if($chongci){
			$chongci=$chongci;				
		}else{
			$chongci=0;
		}	
		
		return $chongci;
	}

	 /**
     * 交班记录
     * @author [lx] 
     */
    public function addjb(){
    	$agentinfo = session('storeInfo');
    	$param = input('post.');
		$param['add_time'] = now_time();
		$param['store_id'] = $agentinfo['id'];
		$param['store_name'] = $agentinfo['store_name'];
				
		$employee = session('employee');
		if($employee){
			$param['mobile'] = $employee['mobile'];//员工手机
		}else{
			$param['mobile'] = $agentinfo['store_tel'];//管理员手机
		}
		
		$data['mobile'] = $param['mobile'];
		$data['time'] = now_time();
		$data['zsr'] = input('total_icome');
		if ($this->model->allowField(true)->save($param) !== false) {
			return json(['code'=>200,'data'=>$data]);
		}else{
			return json(['code'=>408,'msg'=>"交班失败"]);
		}
	}
}
